package cn.lovezaoan.hpcenter.manager
{
    import cn.lovezaoan.hpcenter.parse.ExtractCfgManager;
    import cn.lovezaoan.hpcenter.parse.ExtractTypeCfg;
    import cn.lovezaoan.hpcenter.ui.ext.BlogPanel;
    import cn.lovezaoan.hpcenter.ui.ext.FlashPanel;
    import cn.lovezaoan.hpcenter.ui.ext.HtmlPanel;
    import cn.lovezaoan.hpcenter.ui.ext.ListPanel;
    import cn.lovezaoan.hpcenter.ui.ext.PanelBase;
    import cn.lovezaoan.hpcenter.ui.ext.TiebaPanel;
    import cn.lovezaoan.hpcenter.ui.ext.player.AudioPlayer;
    
    import com.esria.samples.dashboard.events.LayoutChangeEvent;
    import com.esria.samples.dashboard.managers.PodLayoutManager;
    import com.esria.samples.dashboard.managers.StateManager;
    import com.esria.samples.dashboard.view.Pod;
    
    import flash.utils.Dictionary;
    
    import mx.collections.ArrayList;
    import mx.containers.Canvas;
    import mx.containers.ViewStack;
    import mx.effects.Sequence;
    import mx.events.IndexChangedEvent;
    import mx.utils.ArrayUtil;
    
    /**
     * 初始化管理类。
	 * 
	 * 注意几个概念间的关系：
	 * tab下面有一个pod，pod里面有多个PanelBase。
     *
     * */
    public class InitManager
    {
        private static var _instance:InitManager = new InitManager(InitManagerEnforcer);
		
		private static var _podHash:Object;
		private static var _podDataDictionary:Dictionary;
		private static var _podLayoutManagers:Array;
		private static var _mainWin:Object;
        
        public static function getInstance(mainWin:Object,podLayoutManagers:Array,podDataDictionary:Dictionary,podHash:Object):InitManager
        {
			_mainWin = mainWin;
			_podHash =podHash;
			_podLayoutManagers = podLayoutManagers;
			_podDataDictionary = podDataDictionary;
            return _instance;
        }
        
        public function InitManager(enforcer:Class)
        {
            if (enforcer != InitManagerEnforcer)
            {
                throw new Error("Use InitManager.getInstance to get the only instance of Class InitMananger");
            }
        }
		
		/**
		 * 根据配置文件初始化一个ViewStack
		 *
		 * */
		public function initViewStack(viewStack:ViewStack, podDataDictionary:Dictionary,
									  podLayoutManagers:Array):void
		{
			var cfgs:ArrayList = findCfgs();
			
			if (cfgs != null)
			{
				var tabs:Array = parseCfgs(cfgs);
				addCanvas2ViewStack(viewStack, tabs, podDataDictionary, podLayoutManagers);
			}
		}
        
        /**
         * 初始化指定的Pod布局管理器PodLayoutManager中的所有Pod，并返回最后一个Pod
         *
         * */
        public function initPod(index:int,panelEffect:Sequence,onChangePodView:Function):Pod
        {
            var tab:Object = _podDataDictionary[_podLayoutManagers[index]] as Object;
			var pod:Pod = null;
            if (tab != null)
            {
				var unsavedPodCount:int = 0;
                if ( tab.sites != null )
                {
					pod = new Pod();
					unsavedPodCount = addPanelBase2Pod( index,pod,tab, 1,unsavedPodCount,panelEffect,onChangePodView);
                }
                else
                {
                	var tabPodObject:Object = tab.pod;
					if( tabPodObject != null  )
					{
						var panelBasesLen = ArrayUtil.toArray(tabPodObject).length;
						for( var podName:String in tabPodObject )
						{
							pod = new Pod();
							unsavedPodCount = addPanelBase2Pod(index,pod,tabPodObject[podName], panelBasesLen,unsavedPodCount,panelEffect,onChangePodView);
						}
					}
                }
            }
            
            return pod;
        }
		
		private function addPanelBase2Pod(podIndex:int, pod:Pod,panelData:Object, panelBasesLen:int,unsavedPodCount:int,panelEffect:Sequence,
										  onChangePodView:Function):int
		{
			var podContent:PanelBase;
			var message:ArrayList = new ArrayList();
			var msg:Message;
			var tiebas:Dictionary= new Dictionary();
			var podLayoutManager:PodLayoutManager = _podLayoutManagers[podIndex];
			
			pod.id = panelData.id;
			pod.title = panelData.label;
			var displayType:String = panelData.displayType;
			var metaData:Array = new Array();
			var mgr:PortalManager = new PortalManager(panelData.id, displayType, _mainWin, podLayoutManager.id);
			mgr.requestMessagesByTypeAndAsyncResponse();
			switch (displayType)
			{
				case Portal.PANEL_FLASH:
					podContent = new FlashPanel();
					break;
				case Portal.PANEL_HTML:
				case Portal.PANEL_TAB:
					var url:String = "";
					if( displayType == Portal.PANEL_TAB)
					{
						url = panelData.sites[0].url;
					}else
					{
						url = panelData.url;
					}
					podContent = new HtmlPanel();
					msg = new Message("text1", "2010-2-1", url, "hua");
					break;
				case Portal.PANEL_BLOG:
					podContent = new BlogPanel();
					metaData["tabBar"] = _mainWin.tabBar;
					metaData["viewStack"] = _mainWin.viewStack;
					podContent.metadata = metaData;
					break;
				case Portal.PANEL_AUDIO:
					podContent = new AudioPlayer();
					break;
				case Portal.PANEL_TIEBA:
					podContent = new TiebaPanel();
					tiebas[panelData.id] =  podContent;
					metaData["tabBar"] = _mainWin.tabBar;
					metaData["viewStack"] = _mainWin.viewStack;
					podContent.metadata = metaData;
					(tiebas[panelData.id] as TiebaPanel).addNewTieba(panelData.id,panelData.label, panelData.sites[0].url);
					if( "children" in panelData &&  panelData.children!=null)
					{
						var tbs:Array = ArrayUtil.toArray( panelData.children );
						var tb:Object;
						for(var i:String in panelData.children )
						{
							tb = panelData.children[i] as Object;
							(tiebas[panelData.id] as TiebaPanel).addNewTieba(tb.id, tb.label, tb.sites[0].url);
						}
					}
					(tiebas[panelData.id] as TiebaPanel).initByFirstTieba();
					break;
				default:
					podContent = new ListPanel();
					
					metaData["tabBar"] = _mainWin.tabBar;
					metaData["viewStack"] = _mainWin.viewStack;
					podContent.metadata = metaData;
			}
			message.addItem(msg);
			podContent.messages = message;
			pod.addChild(podContent);
			
			panelEffect.target = pod;
			panelEffect.play();
			
			var index:Number;
			if (StateManager.isPodMinimized(podLayoutManager.id, pod.id))
			{
				index = StateManager.getMinimizedPodIndex(podLayoutManager.id, pod.id);
				podLayoutManager.addMinimizedItemAt(pod, index);
			}
			else
			{
				index = StateManager.getPodIndex(podLayoutManager.id, pod.id);
				// If the index hasn't been saved move the pod to the last position.
				if (index == -1)
				{
					index = panelBasesLen + unsavedPodCount;
					unsavedPodCount += 1;
				}
				
				podLayoutManager.addItemAt(pod, index, StateManager.isPodMaximized(podLayoutManager.id, pod.id));
			}
			pod.addEventListener(IndexChangedEvent.CHANGE, onChangePodView);
			_podHash[pod] = podLayoutManager;
			
			return unsavedPodCount;
		}
        
        
        
        private function addCanvas2ViewStack(viewStack:ViewStack, tabs:Array, podDataDictionary:Dictionary,
                                             podLayoutManagers:Array):void
        {
            if (tabs != null)
            {
                var tab:Object;
                var canvas:Canvas;
				for(var i:int=0; i < tabs.length; i++)
				{
					tab = tabs[i] as Object;
					canvas = getLabel(tab.label, tab.id, tab, podDataDictionary, podLayoutManagers);
					viewStack.addChild(canvas);
				}
            }
        }
        
        private function existsInSomePod(tabs:Object, parentId:int):Object
        {
            if (tabs != null)
            {
                var tab:Object;
                var pod:Object;
                var panel:Object;
                for (var name:String in tabs)
                {
                    tab = tabs[name] as Object;
                    if ("pod" in tab && tab.pod != null)
                    {
                        pod = tab.pod;
                        for (var n:String in pod)
                        {
							panel = pod[n] as Object;
                            if (panel.id == parentId)
                            {
                                return panel;
                            }
                        }
                    }
                    
                }
            }
            
            return null;
        }
        
        private function findCfgs():ArrayList
        {
            var cfgMgr:ExtractCfgManager = ExtractCfgManager.getExtractCfgManager();
            return cfgMgr.extractTypeCfgs;
        }
        
        private function getLabel(lable:String, id:String, portals:Object, podDataDictionary:Dictionary,
                                  podLayoutManagers:Array):Canvas
        {
            var canvas:Canvas = new Canvas();
            canvas.horizontalScrollPolicy = "off";
            canvas.verticalScrollPolicy = "off";
            canvas.percentWidth = 200;
            canvas.percentHeight = 200;
            canvas.label = lable;
            canvas.id = id;
            
            // Create a manager for each view.
            var manager:PodLayoutManager = new PodLayoutManager();
            manager.container = canvas;
            manager.id = id; //获取ID属性
            manager.addEventListener(LayoutChangeEvent.UPDATE, StateManager.setPodLayout);
            podDataDictionary[manager] = portals;
            podLayoutManagers.push(manager); //装TAB
            return canvas;
        
            //			return null;
        }
        
        private function initTabsAndPodsData(cfg:ExtractTypeCfg, data:Object, isTab:Boolean):Object
        {
            data.id = cfg.id;
            data.label = cfg.name;
            data.parentId = cfg.parentId;
            data.displayType = cfg.displayType;
            data.sites = cfg.siteCfgs != null ? cfg.siteCfgs.toArray() : null;
            if (isTab)
            {
                data.pod = new Object();
            }
            return data;
        }
        
        private function parseCfgs(cfgs:ArrayList):Array
        {
            var tabs:Object = new Object();
            var displayType:String = null;
            var cfg:ExtractTypeCfg = null;
            var id:int = 0;
            var parentId:int = 0;
			var tabsArr:Array = new Array();
			var tabsIndex:int = 0;
            for (var i = 0; i < cfgs.length; i++)
            {
                cfg = cfgs.getItemAt(i) as ExtractTypeCfg;
                displayType = cfg.displayType;
                id = cfg.id;
                parentId = cfg.parentId;
                switch (displayType)
                {
                    case "tab":
                        if (!(id in tabs))
                        {
                            tabs[id] = new Object();
                            tabs[id] = initTabsAndPodsData(cfg, tabs[id], true);
							tabsArr[tabsIndex++] = tabs[id];
                        }
                        break;
                    default:
                        // if its parent has exists
                        if (parentId in tabs)
                        {
                            tabs[parentId].pod[id] = new Object();
                            tabs[parentId].pod[id] = initTabsAndPodsData(cfg, tabs[parentId].pod[id], false);
                        }
                        else
                        {
                            var parentPanelBase:Object = existsInSomePod(tabs, parentId);
                            if (parentPanelBase != null)
                            {
                                if (!("children" in parentPanelBase))
                                {
									parentPanelBase.children = new Object();
                                }
								parentPanelBase.children[id] = new Object();
								parentPanelBase.children[id] = initTabsAndPodsData(cfg, parentPanelBase.children[id], false);
                            }
                        }
                        break;
                }
            }
            
            return tabsArr;
        }
    }

}

class InitManagerEnforcer
{
}